using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using NTTHAO.Web.BL.Rss;
using NTTHAO.Common;
using NTTHAO.Web.Rss;
using System.Globalization;
using NTTHAO.Web.BL.Log;


namespace NTTHAO.CommonWeb
{
    /// <summary>
    /// Summary description for GlobalUpdateRssNews
    /// </summary>
    public class GlobalUpdateRssNews
    {
        public static void UpdateNews(int groupID, int menuID)
        {
            try
            {
                RssGroupTree tree = RssPageGroup.GetTree(groupID);
                if (tree == null) return;

                RssMenuNode node = tree.Node;
                while (node != null && node.Menu.ID != menuID)
                {
                    if (node.Children != null)
                    {
                        node = node.Children[0];
                    }
                    else if (node.NextNode != null)
                    {
                        node = node.NextNode;
                    }
                    else
                    {
                        bool next = false;
                        while (!next && node != null)
                        {
                            node = node.Parent;
                            if (node != null && node.NextNode != null)
                            {
                                node = node.NextNode;
                                next = true;
                            }
                        }
                    }
                }

                if (node == null) return; // menu not found
                RssMenuNode parentNode = node.Parent;

                do
                {
                    if (node.Menu.ID > 0)
                    {
                        // insert RSS here
                        GlobalUpdateRssNews.UpdateNews(node.Menu.ID);
                    }

                    if (node.Children != null)
                    {
                        node = node.Children[0];
                    }
                    else if (node.NextNode != null)
                    {
                        node = node.NextNode;
                    }
                    else
                    {
                        bool next = false;
                        while (!next && node != null)
                        {
                            node = node.Parent;
                            if (node != null && node.NextNode != null)
                            {
                                node = node.NextNode;
                                next = true;
                            }
                        }
                    }
                } while (node != null && (node.Menu.ID != menuID && !node.Parent.Equals(parentNode) && !node.Equals(parentNode)));
            }
            catch { }
        }

        public static void UpdateNews(int menuID)
        {
            try
            {
                DataTable tb = RssMenuLink.GetAllLinks(menuID, -1, 1);
                if (tb != null)
                {
                    foreach (DataRow row in tb.Rows)
                    {
                        try
                        {
                            int linkID = (int)row[RssLink.ID__COLUMN_NAME];
                            int siteID = (int)row[RssLink.RSSSITEID__COLUMN_NAME];
                            string rssUrl = row[RssLink.RSSURL__COLUMN_NAME].ToString();

                            RssSite site = RssSite.GetSite(siteID);
                            if (site == null)
                                continue;

                            string rssContent = WebClientUtilities.ReadContent(rssUrl, System.Text.Encoding.UTF8);
                            RssDocument rssDoc = new RssDocument(rssContent, CultureInfo.CreateSpecificCulture(site.Culture), site.DescriptionEncoded);

                            if (rssDoc.Items != null && rssDoc.Items.Count > 0)
                            {
                                foreach (RssItem item in rssDoc.Items)
                                {
                                    bool existing = false;
                                    if (site.TimeZone >= -12)
                                    {
                                        item.Date = item.Date.AddHours(site.TimeZone - 7);
                                    }
                                    RssContent content = RssContent.TryInsert(linkID, item.Title, item.Description, item.Image, item.Link, item.Date, true, out existing);
                                    RssContentInMenu.TryInsert(menuID, content.ID, true, out existing);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error("GlobalUpdateRssNews", String.Format("GlobalUpdateRssNews.UpdateNews with url: {0}", row[RssLink.RSSURL__COLUMN_NAME].ToString()), ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("NTTHAO.CommonWeb.GlobalUpdateRssNews", String.Format("GlobalUpdateRssNews.UpdateNews ({0})", menuID), ex);
            }
        }

        public static void UpdateAll()
        {
            try
            {
                DataTable tb = RssMenuLink.GetAllLinks(1);
                if (tb != null)
                {
                    foreach (DataRow row in tb.Rows)
                    {
                        RssLink link = new RssLink();
                        link.FromDataRow(row);

                        GlobalUpdateRssNews.UpdateLink(link);

                        //_Log.Debug("Update RSS: " + link.RssUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("NTTHAO.CommonWeb.GlobalUpdateRssNews", "GlobalUpdateRssNews.UpdateAll", ex);
            }
        }

        public static void UpdateLink(RssLink link)
        {
            try
            {
                System.Net.WebClient client = new System.Net.WebClient();
                client.Encoding = System.Text.Encoding.UTF8;
                client.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(UpdateLink_DownloadRssCompleted);
                client.DownloadStringAsync(new Uri(link.RssUrl), link);
            }
            catch {} // (Exception ex)
            //{
            //    _Log.Error(String.Format("GlobalUpdateRssNews.UpdateLink ({0})", link.RssUrl), ex);
            //}
        }

        private static void UpdateLink_DownloadRssCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    return;
                }

                RssLink link = (RssLink)e.UserState;
                RssSite site = RssSite.GetSite(link.RssSiteID);
                string rssContent = e.Result;

                RssDocument rssDoc = new RssDocument(rssContent, CultureInfo.CreateSpecificCulture(site.Culture), site.DescriptionEncoded);

                if (rssDoc.Items != null && rssDoc.Items.Count > 0)
                {
                    foreach (RssItem item in rssDoc.Items)
                    {
                        bool existing = false;
                        if (site.TimeZone >= -12)
                        {
                            item.Date = item.Date.AddHours(site.TimeZone - 7);
                        }
                        RssContent content = RssContent.TryInsert(link.ID, item.Title, item.Description, item.Image, item.Link, item.Date, true, out existing);

                        DataTable tb = RssMenuLink.GetAllMenus(link.ID, -1, 1);
                        if (tb != null)
                        {
                            foreach (DataRow row in tb.Rows)
                            {
                                int menuID = (int)row[RssMenu.ID__COLUMN_NAME];
                                RssContentInMenu.TryInsert(menuID, content.ID, true, out existing);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                RssLink link = (RssLink)e.UserState;

                Logger.Error("NTTHAO.CommonWeb.GlobalUpdateRssNews", String.Format("GlobalUpdateRssNews.UpdateLink_DownloadRssCompleted ({0}) \n Content: \n{1}", link.RssUrl, e.Result), ex);
            }
        }
    }
}
